package com.dy.yunying.biz.service.datacenter.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.datacenter.dto.AdOverviewDto2;
import com.dy.yunying.api.datacenter.vo.AdDataAnalysisVO;
import com.dy.yunying.api.datacenter.vo.PlanAttrAnalyseSearchVo;
import com.dy.yunying.api.datacenter.vo.PlanBaseAttrVo;
import com.dy.yunying.api.dto.AdOverviewDto;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.vo.AdPlanOverviewVo;
import com.dy.yunying.biz.dao.clickhouse3399.AdOverviewMapper;
import com.dy.yunying.biz.dao.datacenter.impl.AdAnalysisDao;
import com.dy.yunying.biz.dao.datacenter.impl.AdPlanAttrStatDao;
import com.dy.yunying.biz.service.datacenter.AdOverviewService;
import com.dy.yunying.biz.service.manage.*;
import com.dy.yunying.biz.utils.DateUtils;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.admin.api.vo.UserSelectVO;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AdPlan;
import com.pig4cloud.pig.api.enums.GdtScheduleTypeEnum;
import com.pig4cloud.pig.api.feign.RemoteAccountService;
import com.pig4cloud.pig.api.feign.RemoteAdPlanService;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.vo.PlanGdtAttrAnalyseReportVo;
import com.pig4cloud.pig.api.vo.PlanTtAttrAnalyseReportVo;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlanAttrStatTypeEnum;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Deprecated
@Slf4j
@Service(value = "dcAdOverviewServiceImpl")
public class AdOverviewServiceImpl implements AdOverviewService {

	@Autowired
	private AdAnalysisDao adAnalysisDaoNew;

	@Autowired
	private AdPlanAttrStatDao adPlanAttrStatDaoNew;

	@Autowired
	private AdOverviewMapper adOverviewMapper;

	@Autowired
	private AdRoleUserService adRoleUserService;

	@Autowired
	private ParentGameService parentGameService;

	@Autowired
	private GameService gameService;

	@Autowired
	AdRoleGameService adRoleGameService;

	@Autowired
	private RemoteAccountService remoteAccountService;

	@Autowired
	private RemoteAdPlanService remoteAdPlanService;

	@Value("${spring.profiles.active}")
	private String profilesActive;

	@Autowired
	private GameChannelPackService gameChannelPackService;

	@Autowired
	private ChannelManageService channelManageService;

	private static final String RETURN_STATUS_ALL_DELETE = "所有包含已删除";
	private static final String NATURAL_FLOW = "自然量";

	/**
	 * 广告数据分析表总数查询
	 *
	 * @param req
	 * @return
	 */
	@Override
	public R countDataTotal(AdOverviewDto2 req) {
		Long count = null;
		try {

			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
				roleUserIdList.addAll(ownerRoleUserIds);
			}

			// 授权的广告账户
			List<String> roleAdAccountList = new ArrayList<>();
			req.setRoleAdAccountList(roleAdAccountList);
			final List<String> accountList2 = remoteAccountService.getAccountList2(roleUserIdList, SecurityConstants.FROM_IN);
			if (ObjectUtils.isNotEmpty(accountList2)) {
				roleAdAccountList.addAll(accountList2);
			}

//		roleAdAccountList.addAll(accountList2);
			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(1)) {
				req.setIsSys(1);
			}

			count = adAnalysisDaoNew.countDataTotal(req);
		} catch (Exception e) {
			log.error("countDataTotal:[{}]", e);
			return R.failed("广告数据分析报表总记录数查询失败");
		}
		return R.ok(count);
	}

	/**
	 * 广告数据分析表分页列表查询
	 *
	 * @param req
	 * @return
	 */
	@Override
	public R list(AdOverviewDto2 req) {
		// 当前用户
		final PigUser user = SecurityUtils.getUser();
		List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
		// 当前账号及管理的账号
		List<Integer> roleUserIdList = new ArrayList<>();
		req.setRoleUserIdList(roleUserIdList);
		roleUserIdList.add(user.getId());
		if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
			roleUserIdList.addAll(ownerRoleUserIds);
		}

		// 授权的广告账户
		List<String> roleAdAccountList = new ArrayList<>();
		req.setRoleAdAccountList(roleAdAccountList);
		final List<String> accountList2 = remoteAccountService.getAccountList2(roleUserIdList, SecurityConstants.FROM_IN);
		if (ObjectUtils.isNotEmpty(accountList2)) {
			roleAdAccountList.addAll(accountList2);
		}

//		roleAdAccountList.addAll(accountList2);
		// 判断是否管理员
		if (SecurityUtils.getRoles().contains(1)) {
			req.setIsSys(1);
		}
		List<AdDataAnalysisVO> adPlanOverviewVoList = adAnalysisDaoNew.list(req); // 查询数据
		deal(adPlanOverviewVoList, req);
		return R.ok(adPlanOverviewVoList);
	}

	/**
	 * 计划属性分析表总数查询
	 *
	 * @param req
	 * @return
	 */
	@Override
	public R<Long> countDataTotal(PlanAttrAnalyseSearchVo req) {
		try {
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
				roleUserIdList.addAll(ownerRoleUserIds);
			}
			// 授权的广告账户
			List<String> roleAdAccountList = new ArrayList<>();
			req.setRoleAdAccountList(roleAdAccountList);
			final List<String> accountList2 = remoteAccountService.getAccountList2(roleUserIdList, SecurityConstants.FROM_IN);
			if (CollectionUtil.isNotEmpty(accountList2)) {
				roleAdAccountList.addAll(accountList2);
			}
			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(1)) {
				req.setIsSys(1);
			}
			List<String> qcs = req.getQueryColumn();
			if (CollectionUtil.isEmpty(qcs)) {
				req.setQueryColumn(PlanAttrStatTypeEnum.ADID.V());
			} else if (!PlanAttrStatTypeEnum.contain(qcs.get(0))) {
				req.setQueryColumn(PlanAttrStatTypeEnum.ADID.V());
			} else {
				req.setQueryColumn(qcs.get(0));
			}
			req.setGameIds(adRoleGameService.getOwnerRoleGameIds());
			//查询总记录数
			Long count = adPlanAttrStatDaoNew.countDataTotal(req);
			return R.ok(count);
		} catch (Exception e) {
			log.error("countDataTotal:[{}]", e);
			return R.failed("计划属性总记录数查询失败");
		}

	}

	/**
	 * 计划属性分析表分页列表查询
	 *
	 * @param page
	 * @param searchVo
	 * @return
	 */
	@Override
	public R selectPlanAttrAnalyseReoport(Page page, PlanAttrAnalyseSearchVo searchVo) {
		// 当前用户
		final PigUser user = SecurityUtils.getUser();
		List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
		// 当前账号及管理的账号
		List<Integer> roleUserIdList = new ArrayList<>();
		searchVo.setRoleUserIdList(roleUserIdList);
		roleUserIdList.add(user.getId());
		if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
			roleUserIdList.addAll(ownerRoleUserIds);
		}
		// 授权的广告账户
		List<String> roleAdAccountList = new ArrayList<>();
		searchVo.setRoleAdAccountList(roleAdAccountList);
		final List<String> accountList2 = remoteAccountService.getAccountList2(roleUserIdList, SecurityConstants.FROM_IN);
		if (CollectionUtil.isNotEmpty(accountList2)) {
			roleAdAccountList.addAll(accountList2);
		}
		// 判断是否管理员
		if (SecurityUtils.getRoles().contains(1)) {
			searchVo.setIsSys(1);
		}
		List<String> qcs = searchVo.getQueryColumn();
		if (CollectionUtil.isEmpty(qcs)) {
			searchVo.setQueryColumn(PlanAttrStatTypeEnum.ADID.V());
		} else if (!PlanAttrStatTypeEnum.contain(qcs.get(0))) {
			searchVo.setQueryColumn(PlanAttrStatTypeEnum.ADID.V());
		} else {
			searchVo.setQueryColumn(qcs.get(0));
		}
		searchVo.setGameIds(adRoleGameService.getOwnerRoleGameIds());
		//根据投放人获取广告账户
//		List<PlanBaseAttrVo> values = adPlanAttrStatDaoNew.selectPlanAttrAnalyseReoport(searchVo);
//		dealPlan(values, searchVo);
//		dealZrl(values, searchVo);
//		return dealStatType(values, searchVo);
		return null;
	}

	private void deal(List<AdDataAnalysisVO> adPlanOverviewVoList, AdOverviewDto2 req) {
		if (CollectionUtils.isNotEmpty(adPlanOverviewVoList)) {

			//分包编码名称
			List<String> appChlArr = new ArrayList<>();
			// 主渠道cdoe
			List<String> channelCodeArr = Lists.newArrayList();

			if (ObjectUtils.isNotEmpty(adPlanOverviewVoList)) {
				adPlanOverviewVoList.forEach(dataAccount -> {
					String appchl = dataAccount.getAppchl();
					if (StringUtils.isNotBlank(appchl)) {
						appChlArr.add(appchl);
					}
					//主渠道
					String channelCode = dataAccount.getParentchl();
					if (StringUtils.isNotBlank(channelCode)) {
						channelCodeArr.add(channelCode);
					}
				});
			}
			List<Map<String, String>> appChlArrList = gameChannelPackService.queryAppChlName(appChlArr);
			Map<String, String> mapappChl = new HashMap<>();
			if (ObjectUtils.isNotEmpty(appChlArrList)) {
				appChlArrList.forEach(appChlData -> {
					mapappChl.put(String.valueOf(appChlData.get("code")), appChlData.get("codeName"));
				});
			}

			// 渠道list
			Map<String, String> channelMap = new HashMap<>();
			if (channelCodeArr.size() > 0) {
				QueryWrapper<ChannelManageDO> wrapper = new QueryWrapper();
				wrapper.in("chncode", channelCodeArr);
				wrapper.eq("pid", 0);
				List<ChannelManageDO> channelManageDOList = channelManageService.list(wrapper);
				if (ObjectUtils.isNotEmpty(channelManageDOList)) {
					channelMap = channelManageDOList.stream().collect(Collectors.toMap(item -> {
						return item.getChncode();
					}, ChannelManageDO::getChnname));
				}
			}


			for (AdDataAnalysisVO adDataAnalysisVO : adPlanOverviewVoList) {
				try {
					final Long pgid = adDataAnalysisVO.getPgid();
					final Long gameid = adDataAnalysisVO.getGameid();

					final ParentGameDO parentGameDO = parentGameService.getByPK(pgid);
					String parentGameName = "-";
					if (parentGameDO != null) {
						parentGameName = parentGameDO.getGname();
					}
					adDataAnalysisVO.setParentGameName(parentGameName);

					final WanGameDO wanGameDO = gameService.selectVOByPK(gameid);
					String gameName = "-";
					if (wanGameDO != null) {
						gameName = wanGameDO.getGname();
					}
					adDataAnalysisVO.setGameName(gameName);
					if (StringUtils.isNotBlank(req.getQueryColumn())) {
						if (StringUtils.isNotBlank(adDataAnalysisVO.getStartTime())) {
							String schduleType = adDataAnalysisVO.getStartTime() + "至" + (StringUtils.isNotBlank(adDataAnalysisVO.getEndTime()) ? adDataAnalysisVO.getEndTime() : "不限");
							adDataAnalysisVO.setScheduleType(schduleType);
						}
						adDataAnalysisVO.setStatus(transValue(adDataAnalysisVO.getStatus()));
						adDataAnalysisVO.setDeliveryRange(transValue(adDataAnalysisVO.getDeliveryRange()));
						adDataAnalysisVO.setUnionVideoType(transValue(adDataAnalysisVO.getUnionVideoType()));
						adDataAnalysisVO.setInventoryType(inventory(adDataAnalysisVO.getInventoryType()));
					}

					//分包编码名称
					String appchl = adDataAnalysisVO.getAppchl();
					adDataAnalysisVO.setAppchl(mapappChl.get(appchl) == null ? appchl : mapappChl.get(appchl));

					String parentchl = adDataAnalysisVO.getParentchl();
					adDataAnalysisVO.setParentchlname(channelMap.get(parentchl) == null ? parentchl : channelMap.get(parentchl));

					// 广点通》计划类别》计划时间戳格式化
					if (PlatformTypeEnum.GDT.getValue().equals(req.getPlatformType())) {
						if (StringUtils.isNotBlank(req.getQueryColumn()) && req.getQueryColumn().indexOf("adid") >= 0) {
							String createTime = adDataAnalysisVO.getCreateTime();
							String updateTime = adDataAnalysisVO.getUpdateTime();
							if (StringUtils.isNotBlank(createTime)) {
								adDataAnalysisVO.setCreateTime(DateUtils.timeStamp2Date(createTime, DateUtils.YYYY_MM_DD_HH_MM_SS));
							}
							if (StringUtils.isNotBlank(updateTime)) {
								adDataAnalysisVO.setUpdateTime(DateUtils.timeStamp2Date(updateTime, DateUtils.YYYY_MM_DD_HH_MM_SS));
							}
						}
					}

					// 处理自然量
					if (StringUtils.isNotBlank(req.getQueryColumn())) {
						if (req.getCycleType() != null) {
							if (req.getQueryColumn().contains("adid") && !req.getQueryColumn().contains("advertiserid")) {
								adDataAnalysisVO.setAdidName(StringUtils.isBlank(adDataAnalysisVO.getAdid()) ? "自然量" : adDataAnalysisVO.getAdidName());
							}
							if (req.getQueryColumn().contains("advertiserid") && !req.getQueryColumn().contains("adid")) {
								adDataAnalysisVO.setAdAccountName(StringUtils.isBlank(adDataAnalysisVO.getAdvertid()) ? "自然量" : adDataAnalysisVO.getAdAccountName());
							}
							if (req.getQueryColumn().contains("advertiserid") && req.getQueryColumn().contains("adid")) {
								adDataAnalysisVO.setAdidName(StringUtils.isBlank(adDataAnalysisVO.getAdid()) ? "自然量" : adDataAnalysisVO.getAdidName());
							}
						}
					}
				} catch (Exception e) {
					log.error("数据处理异常", e);
				}
			}
		}
	}


	/**
	 * 根据类型转换为对应的中文显示
	 *
	 * @param type
	 * @return
	 */
	private String transValue(String type) {
		if (StringUtils.isNotBlank(type)) {
			switch (type) {
				case "001":
					return "动游科技";
				case "INVENTORY_AWEME_FEED":
					return "抖音信息流";
				case "INVENTORY_VIDEO_FEED":
					return "西瓜信息流";
				case "INVENTORY_FEED":
					return "头条信息流";
				case "INVENTORY_TEXT_LINK":
					return "头条文章详情页";
				case "INVENTORY_HOTSOON_FEED":
					return "火山信息流";
				case "INVENTORY_UNION_SLOT":
					return "穿山甲";
				case "UNION_BOUTIQUE_GAME":
					return "穿山甲精选休闲游戏";
				case "INVENTORY_UNION_SPLASH_SLOT":
					return "穿山甲开屏广告";
				case "INVENTORY_AWEME_SEARCH":
					return "搜索广告——抖音位";
				case "INVENTORY_SEARCH":
					return "搜索广告——头条位";
				case "INVENTORY_UNIVERSAL":
					return "通投智选";
				case "INVENTORY_BEAUTY":
					return "轻颜相机";
				case "INVENTORY_PIPIXIA":
					return "皮皮虾";
				case "INVENTORY_AUTOMOBILE":
					return "懂车帝";
				case "INVENTORY_STUDY":
					return "好好学习";
				case "INVENTORY_FACE_U":
					return "faceu";
				case "OTHER":
					return "其他";

				case "LINK":
					return "销售线索收集";
				case "APP":
					return "应用推广";
				case "DPA":
					return "商品目录推广";
				case "GOODS":
					return "商品推广";
				case "STORE":
					return "门店推广";
				case "AWEME":
					return "抖音号推广";
				case "SHOP":
					return "电商店铺推广";
				case "ARTICAL":
					return "头条文章推广";

				case "BUDGET_MODE_DAY":
					return "日预算";
				case "BUDGET_MODE_TOTAL":
					return "总预算";
				case "BUDGET_MODE_INFINITE":
					return "不限";


//			   广告计划状态
				case "AD_STATUS_ENABLE":
					return "启用";
				case "AD_STATUS_DISABLE":
					return "计划暂停";
				case "AD_STATUS_CAMPAIGN_DISABLE":
					return "已被广告组暂停";
				case "AD_STATUS_DELIVERY_OK":
					return "投放中";
				case "AD_STATUS_REAUDIT":
					return "修改审核中";
				case "AD_STATUS_AUDIT":
					return "新建审核中";
				case "AD_STATUS_DONE":
					return "已完成（投放达到结束时间）";
				case "AD_STATUS_CREATE":
					return "计划新建";
				case "AD_STATUS_AUDIT_DENY":
					return "审核不通过";
				case "AD_STATUS_BALANCE_EXCEED":
					return "账户余额不足）";
				case "AD_STATUS_BUDGET_EXCEED":
					return "超出预算";
				case "AD_STATUS_NOT_START":
					return "未到达投放时间";
				case "AD_STATUS_NO_SCHEDULE":
					return "不在投放时段";
				case "AD_STATUS_DELETE":
					return "已删除";
				case "AD_STATUS_CAMPAIGN_EXCEED":
					return "广告组超出预算";
				case "AD_STATUS_ALL":
					return RETURN_STATUS_ALL_DELETE;
				case "AD_STATUS_NOT_DELETE":
					return "所有不包含已删除";

				//广点通
				case "STATUS_UNKNOWN":
					return "未知状态";
				case "STATUS_DENIED":
					return "审核不通过";
				case "STATUS_FROZEN":
					return "冻结";
				case "STATUS_SUSPEND":
					return "暂停中";
				case "STATUS_READY":
					return "未到投放时间";
				case "STATUS_ACTIVE":
					return "投放中";
				case "STATUS_STOP":
					return "投放结束";
				case "STATUS_PREPARE":
					return "准备中";
				case "STATUS_DELETED":
					return "已删除";

				case "STATUS_ACTIVE_ACCOUNT_FROZEN":
					return "广告被暂停（账户资金被冻结）";
				case "STATUS_ACTIVE_ACCOUNT_EMPTY":
					return "广告被暂停（账户余额不足）";
				case "STATUS_ACTIVE_ACCOUNT_LIMIT":
					return "广告被暂停（账户达日限额）";
				case "STATUS_ACTIVE_CAMPAIGN_LIMIT":
					return "广告被暂停（推广计划达日限额））";
				case "STATUS_ACTIVE_CAMPAIGN_SUSPEND":
					return "广告被暂停（推广计划暂停）";
				case "STATUS_PART_READY":
					return "部分待投放";
				case "STATUS_PART_ACTIVE":
					return "部分投放中";


				case "1":
					return "头条";
				case "2":
					return "广点通";

				case "REWARDED_VIDEO":
					return "激励视频";
				case "ORIGINAL_VIDEO":
					return "原生";
				case "SPLASH_VIDEO":
					return "开屏";

				case "UNIVERSAL":
					return "通投智选";
				case "DEFAULT":
					return "默认";
				case "UNION":
					return "穿山甲";

				case "DOWNLOAD_URL":
					return "下载链接";
				case "QUICK_APP_URL":
					return "快应用+下载链接";
				case "EXTERNAL_URL":
					return "落地页链接";

				/*广告创意状态*/
				case "CREATIVE_STATUS_DELIVERY_OK":
					return "投放中";
				case "CREATIVE_STATUS_NOT_START":
					return "未到达投放时间";
				case "CREATIVE_STATUS_NO_SCHEDULE":
					return "不在投放时段";
				case "CREATIVE_STATUS_DISABLE":
					return "创意暂停";
				case "CREATIVE_STATUS_CAMPAIGN_DISABLE":
					return "已被广告组暂停";
				case "CREATIVE_STATUS_CAMPAIGN_EXCEED":
					return "广告组超出预算";
				case "CREATIVE_STATUS_AUDIT":
					return "新建审核中";
				case "CREATIVE_STATUS_REAUDIT":
					return "修改审核中";
				case "CREATIVE_STATUS_DELETE":
					return "已删除";
				case "CREATIVE_STATUS_DONE":
					return "已完成";
				case "CREATIVE_STATUS_AD_DISABLE":
					return "广告计划暂停";
				case "CREATIVE_STATUS_AUDIT_DENY":
					return "审核不通过";
				case "CREATIVE_STATUS_BALANCE_EXCEED":
					return "超出预算";
				case "CREATIVE_STATUS_PRE_ONLINE":
					return "预上线";
				case "CREATIVE_STATUS_AD_AUDIT":
					return "广告计划新建审核中";
				case "CREATIVE_STATUS_AD_REAUDIT":
					return "广告计划修改审核中";
				case "CREATIVE_STATUS_AD_AUDIT_DENY":
					return "广告计划审核不通过";
				case "CREATIVE_STATUS_ALL":
					return RETURN_STATUS_ALL_DELETE;
				case "CREATIVE_STATUS_NOT_DELETE":
					return "所有不包含已删除";
				case "CREATIVE_STATUS_ADVERTISER_BUDGET_EXCEED":
					return "超出账户日预算";

				/*创意素材类型*/
				case "CREATIVE_IMAGE_MODE_SMALL":
					return "小图，宽高比1.52，大小2M以下，下限：456 & 300，上限：1368 & 900";
				case "CREATIVE_IMAGE_MODE_LARGE":
					return "大图，横版大图宽高比1.78，大小2M以下，下限：1280 & 720，上限：2560 & 1440\t";
				case "CREATIVE_IMAGE_MODE_GROUP":
					return "组图，宽高比1.52，大小2M以下，下限：456 & 300，上限：1368 & 900";
				case "CREATIVE_IMAGE_MODE_VIDEO":
					return "横版视频，封面图宽高比1.78（下限：1280 & 720，上限：2560 & 1440））";
				case "CREATIVE_IMAGE_MODE_LARGE_VERTICAL":
					return "大图竖图，宽高比0.56，大小2M以下，下限：720 & 1280，上限：1440 & 2560";
				case "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL":
					return "竖版视频，封面图宽高比0.56（9:16），下限：720 & 1280，上限：1440 & 2560";
				case "TOUTIAO_SEARCH_AD_IMAGE":
					return "广告计划修改审核中";
				case "SEARCH_AD_SMALL_IMAGE":
					return "搜索小图";
				case "CREATIVE_IMAGE_MODE_UNION_SPLASH":
					return "穿山甲开屏图片";
				case "CREATIVE_IMAGE_MODE_UNION_SPLASH_VIDEO":
					return "穿山甲开屏视频";
				case "CREATIVE_IMAGE_MODE_DISPLAY_WINDOW":
					return "搜索橱窗";
				case "MATERIAL_IMAGE_MODE_TITLE":
					return "标题类型，非创意的素材类型，仅报表接口会区分此素材类型";

				case "SCHEDULE_FROM_NOW":
					return "从今天起长期投放";
				case "SCHEDULE_START_END":
					return "设置开始和结束日期";
//          广点通转换目标
				case "OPTIMIZATIONGOAL_FOLLOW":
					return "关注";
				case "OPTIMIZATIONGOAL_CLICK":
					return "点击";
				case "OPTIMIZATIONGOAL_IMPRESSION":
					return "曝光";
				case "OPTIMIZATIONGOAL_APP_DOWNLOAD":
					return "下载";
				case "OPTIMIZATIONGOAL_APP_ACTIVATE":
					return "激活";
				case "OPTIMIZATIONGOAL_APP_REGISTER":
					return "次日留存";
				case "OPTIMIZATIONGOAL_ONE_DAY_RETENTION":
					return "付费次数，游戏客户如需优化付费行为，建议使用首次付费作为优化目标";
				case "OPTIMIZATIONGOAL_APP_PURCHASE":
					return "下单";
				//          广点通深度优化方式
				case "DEEP_OPTIMIZATION_ACTION_TYPE_DOUBLE_GOAL_BID":
					return "双目标出价";
				case "DEEP_OPTIMIZATION_ACTION_TYPE_TWO_STAGE_BID":
					return "双目标出价";

				default:
					return "-";
			}
		}
		return "-";

	}

	/**
	 * 当数据为数组的时候，返回对应的中文数据
	 *
	 * @param arrs
	 * @return
	 */
	private String inventory(String arrs) {
		if (StringUtils.isBlank(arrs)) {
			return null;
		}

		JSONArray jsonArray = JSON.parseArray(arrs);
		if (null != jsonArray && jsonArray.size() > 0) {
			StringBuffer stringBuffer = new StringBuffer("[");
			jsonArray.forEach(j -> {
				stringBuffer.append(transValue(j.toString()) + ",");
			});
			stringBuffer.delete(stringBuffer.lastIndexOf(","), stringBuffer.length());
			stringBuffer.append("]");
			return stringBuffer.toString();
		}

		return null;
	}

	private void dealZrl(List<PlanBaseAttrVo> values, PlanAttrAnalyseSearchVo searchVo) {
		if (CollectionUtil.isEmpty(values) || (!Objects.isNull(searchVo.getCycleType()) && searchVo.getCycleType() == 4)) {
			return;
		}
		if (searchVo.getQueryColumn().contains(PlanAttrStatTypeEnum.ADID.V()) || searchVo.getQueryColumn().contains(PlanAttrStatTypeEnum.ADVERTISERID.V())) {
			values.forEach(v -> {
				if (StringUtils.isBlank(v.getId())) {
					v.setName(NATURAL_FLOW);
				}
			});
		}
	}


	private R dealStatType(List<PlanBaseAttrVo> values, PlanAttrAnalyseSearchVo searchVo) {

		switch (PlanAttrStatTypeEnum.get(CollectionUtil.isNotEmpty(searchVo.getQueryColumn()) ? searchVo.getQueryColumn().get(0) : Constant.EMPTTYSTR)) {
			case ADID:
				//获取广告信息 TODO
				return doDealAdidStatType(values, searchVo.getCtype());
			default:
				return R.ok(values);
		}
	}

	private void dealPlan(List<PlanBaseAttrVo> values, PlanAttrAnalyseSearchVo searchVo) {
		if (CollectionUtils.isNotEmpty(values)) {
			if (searchVo.getQueryColumn().contains("appchl")) {
				//分包编码名称
				List<String> appChlArr = new ArrayList<>();
				if (ObjectUtils.isNotEmpty(values)) {
					values.forEach(dataAccount -> {
						String appchl = dataAccount.getId();
						if (StringUtils.isNotBlank(appchl)) {
							appChlArr.add(appchl);
						}
					});
				}
				List<Map<String, String>> appChlArrList = gameChannelPackService.queryAppChlName(appChlArr);
				Map<String, String> mapappChl = new HashMap<>();
				if (ObjectUtils.isNotEmpty(appChlArrList)) {
					appChlArrList.forEach(appChlData -> {
						mapappChl.put(String.valueOf(appChlData.get("code")), appChlData.get("codeName"));
					});
				}
				//封装数据
				values.forEach(data -> {
					// 分包编码名称
					String appchl = data.getId();
					data.setName(mapappChl.get(appchl) == null ? appchl : mapappChl.get(appchl));
				});
			}
		}
	}


	private R doDealAdidStatType(List<PlanBaseAttrVo> values, Integer ctype) {
		if (CollectionUtil.isEmpty(values)) {
			return R.ok(values);
		}
		if (!Objects.isNull(ctype) && ctype == Integer.parseInt(PlatformTypeEnum.TT.getValue())) {
			String adids = values.stream().map(v -> v.getId()).filter(v -> StringUtils.isNotBlank(v)).collect(Collectors.joining(Constant.COMMA));
			R<List<AdPlan>> adPlanDetail = null;
			if (StringUtils.isNotBlank(adids)) {
				adPlanDetail = remoteAdPlanService.getByAdids(adids);
				if (adPlanDetail.getCode() != 0) {
					return R.failed("获取广告详情失败");
				}
			}
			List<AdPlan> adPlans = Objects.isNull(adPlanDetail) ? null : adPlanDetail.getData();
			Map<String, AdPlan> adPlanMap = new HashMap<>();
			if (CollectionUtil.isNotEmpty(adPlans)) {
				adPlans.stream().forEach(v -> adPlanMap.put(String.valueOf(v.getAdId()), v));
			}
			return R.ok(values.stream().map(v -> {
				PlanTtAttrAnalyseReportVo vo = BeanUtil.copyProperties(v, PlanTtAttrAnalyseReportVo.class);
				AdPlan adPlan = adPlanMap.get(vo.getId());
				vo.setAdStatus(Objects.isNull(adPlan) ? vo.getAdStatus() : adPlan.getStatus());
				vo.setGender(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getGender());
				vo.setAge(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getAge());
				vo.setRetargetingTagsExclude(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getRetargetingTagsExclude());
				vo.setRetargetingTagsInclude(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getRetargetingTagsInclude());
				vo.setRoiGoal(Objects.isNull(adPlan) ? vo.getRoiGoal() : adPlan.getRoiGoal());
				vo.setActionScene(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getActionScene());
				vo.setActionWords(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getActionWords());
				vo.setInterestCategories(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getInterestCategories());
				vo.setInterestWords(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getInterestWords());
				//是否为智能放量
				vo.setSmartVolume(Objects.isNull(adPlan) ? Constants.NO : Objects.isNull(adPlan.getAutoExtendEnabled()) || adPlan.getAutoExtendEnabled() != 1 ? Constants.NO : Constants.YES);
				vo.setBid(Objects.isNull(adPlan) ? vo.getBid() : adPlan.getBudget());
				vo.setBidType(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getBudgetMode());
				vo.setCpaBid(Objects.isNull(adPlan) ? vo.getCpaBid() : adPlan.getCpaBid());
				vo.setConverType(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getPricing());
				vo.setThrowCountLevel(Objects.isNull(adPlan) ? vo.getThrowCountLevel() : adPlan.getEstimateNum());
				vo.setInventoryType(Objects.isNull(adPlan) ? Constants.EMPTTYSTR : adPlan.getInventoryType());
				if (!Objects.isNull(adPlan) && GdtScheduleTypeEnum.SCHEDULE_FROM_NOW.getType().equals(adPlan.getScheduleType())) {
					vo.setThrowDays(Objects.isNull(adPlan) ? vo.getThrowDays() : (converDay(adPlan.getAdCreateTime(), DateUtil.format(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS), DateUtils.YYYY_MM_DD_HH_MM_SS)));
				} else {
					vo.setThrowDays(Objects.isNull(adPlan) ? vo.getThrowDays() : (converDay(adPlan.getStartTime(), adPlan.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM)));
				}
				vo.setMaterialVos(Objects.isNull(adPlan) ? vo.getMaterialVos() : adPlan.getMaterialVos());
				return vo;
			}).collect(Collectors.toList()));
		}
		if (!Objects.isNull(ctype) && ctype == Integer.parseInt(PlatformTypeEnum.GDT.getValue())) {
			String adids = values.stream().map(v -> v.getId()).filter(v -> StringUtils.isNotBlank(v)).collect(Collectors.joining(Constant.COMMA));
			R<List<PlanGdtAttrAnalyseReportVo>> adPlanDetail = null;
			if (StringUtils.isNotBlank(adids)) {
				adPlanDetail = remoteAdPlanService.getGdtByAdids(adids);
				if (adPlanDetail.getCode() != 0) {
					return R.failed("获取广告详情失败");
				}
			}
			List<PlanGdtAttrAnalyseReportVo> ad = Objects.isNull(adPlanDetail) ? null : adPlanDetail.getData();
			Map<String, PlanGdtAttrAnalyseReportVo> adPlanMap = new HashMap<>();
			if (CollectionUtil.isNotEmpty(ad)) {
				ad.stream().forEach(v -> adPlanMap.put(String.valueOf(v.getId()), v));
			}
			return R.ok(values.stream().map(v -> {
				PlanGdtAttrAnalyseReportVo vo = adPlanMap.get(v.getId());
				if (Objects.isNull(vo)) {
					vo = BeanUtil.copyProperties(v, PlanGdtAttrAnalyseReportVo.class);
				} else {
					BeanUtil.copyProperties(v, vo);
				}
				return vo;
			}).collect(Collectors.toList()));
		}
		return R.ok(values);
	}

	private Long converDay(String startTime, String endTime, String dateFormat) {
		try {
			long hour = DateUtil.between(DateUtil.parse(startTime, dateFormat), DateUtil.parse(endTime, dateFormat), DateUnit.HOUR, false);
			long day = hour % 24 > 0 ? 1 : 0;
			if (hour <= 24) {
				return day;
			} else {
				return DateUtil.between(DateUtil.parse(startTime, dateFormat), DateUtil.parse(endTime, dateFormat), DateUnit.DAY, false) + day;
			}
		} catch (Exception e) {
			return 0l;
		}
	}


	/*
	 *******************************************************************************************************************
	 * 以下为废弃代码
	 *******************************************************************************************************************
	 */

	@Deprecated
	@Override
	public R selectAdOverviewSource(AdOverviewDto req) {
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		//处理请求参数对象
		managerParam(req);
		// 查询列表数据 todo 投放人账号对不上，所有默认先将xml other条件去掉
		req.setIsSys(1);
		IPage<AdPlanOverviewVo> adOverviewVoPage = adOverviewMapper.list(page, req); // 查询数据
		//处理报表数据
		List<AdPlanOverviewVo> adPlanOverviewVoList = adOverviewVoPage.getRecords();
		if (CollectionUtils.isNotEmpty(adPlanOverviewVoList)) {
			List<AdPlanOverviewVo> managerAdPlanStatitic = managerAdPlanStatitic(req, adOverviewVoPage.getRecords());
			adOverviewVoPage.setRecords(managerAdPlanStatitic);
			if (adOverviewVoPage.getTotal() == 0) {
				adOverviewVoPage.setRecords(Lists.newArrayList());
			}
		}
		return R.ok(adOverviewVoPage);


	}

	@Deprecated
	@Override
	public List<AdPlanOverviewVo> excelPlanStatistic(AdOverviewDto req) {
		managerParam(req);
		//处理分页参数
		List<AdPlanOverviewVo> adPlanOverviewVoList = adOverviewMapper.selectAdOverviewSourceTable(req, Boolean.FALSE);
		return managerAdPlanStatitic(req, adPlanOverviewVoList);
	}

	@Deprecated
	public void managerParam(AdOverviewDto req) {
		//当前角色授权的平台账号列表
		List<UserSelectVO> userSelectVOList = adRoleUserService.getOwnerRoleUsers();
		List<Integer> userList = userSelectVOList.stream().map(userSelectVO -> userSelectVO.getUserId()).collect(Collectors.toList());
		List<Integer> queryInvestorList = userList;
		List<Integer> investorList = req.getInvestorList();
		if (CollectionUtils.isNotEmpty(investorList)) {
			//查询当前查询列表，及授权平台账号两个list交集查询
			queryInvestorList = userList.stream().filter(item -> investorList.contains(item)).collect(Collectors.toList());
		}
		//TODO 将当前可查看的平台账号列表 对应的广告账号列表
		R<List<AdAccount>> accountR = remoteAccountService.getAccountListByUserList(queryInvestorList, SecurityConstants.FROM_IN);
		if (CollectionUtils.isNotEmpty(accountR.getData())) {
			List<AdAccount> adAccountList = accountR.getData();
			List<String> adList = adAccountList.stream().map(adAccount -> adAccount.getAdvertiserId()).collect(Collectors.toList());
			List<String> paramAdList = req.getAdvertiserIdList();
			if (CollectionUtils.isNotEmpty(req.getAdvertiserIdList())) {
				adList = adList.stream().filter(item -> paramAdList.contains(item)).collect(Collectors.toList());
			}
			//todo 临时先不加条件筛选--广告账号
			req.setAdvertiserIdArr(String.join(",", adList));

			req.setAdvertiserIdList(adList);
		}
		if (null == req.getCycleType()) {
			//默认汇总查询
			req.setCycleType(4);
		}
		if (StringUtils.isNotBlank(req.getQueryColumn())) {
//类别 多个用逗号分隔【系统 os,主游戏 pgid，子游戏 gid ,部门 deptId,渠道编码 parentchl，分包编码：packCode,广告计划 adId,  投放人investor
			StringBuffer queryBuffer = new StringBuffer();
			for (String column : req.getQueryColumn().split(",")) {
				switch (column) {
					case "adId":
						queryBuffer.append(" a.adname,b.startTime,b.endTime ,b.unionVideoType,b.deliveryRange," +
								"   b.convertId,b.inventoryType," +
								"   b.campaignId,b.campaignName,b.adid,b.adidName,b.budget,b.status," +
								"   b.advertid, b.pricing,b.createTime ," +
//						"   b.updateTime,b.ctype,b.adgroupId,b.convertName,b.deepConvert,"); continue;
								"   b.updateTime,b.ctype,b.adgroupId,b.convertName,b.convertDescri,b.deepConvert,b.deepConvertDescri,");
						continue;

					case "os":
						queryBuffer.append("a.os,");
						continue;
					case "gid":
						queryBuffer.append("a.gname,a.gid,a.ratio,");
						continue;
					case "pgid":
						queryBuffer.append("a.pgid,a.pgame,a.ratio,");
						continue;
					case "deptId":
						queryBuffer.append("a.deptId,a.deptName,");
						continue;
					case "investor":
						queryBuffer.append("a.investor,a.investorname,");
						continue;
					case "parentchl":
						queryBuffer.append("a.parentchl,");
						continue;
					case "packCode":
						queryBuffer.append("a.parentchl,a.packCode,");
						continue;
				}
			}
			String columnString = queryBuffer.toString();
			if (columnString.charAt(columnString.length() - 1) == ',') {
				columnString = columnString.substring(0, columnString.length() - 1);
			}

			req.setQueryColumn(columnString);

		}
	}


	/**
	 * 处理报表数据
	 *
	 * @param req
	 * @param adPlanOverviewVoList
	 * @return
	 */
	@Deprecated
	private List<AdPlanOverviewVo> managerAdPlanStatitic(AdOverviewDto req, List<AdPlanOverviewVo> adPlanOverviewVoList) {
		if (CollectionUtils.isNotEmpty(adPlanOverviewVoList)) {
			if (StringUtils.equals(profilesActive, "dev")) {
				//手动补充广点通数据--便于测试guandia
				AdPlanOverviewVo adPlanOverviewVo = new AdPlanOverviewVo();
				adPlanOverviewVo.setOs("0");
				adPlanOverviewVo.setAdid("430812641");
				adPlanOverviewVo.setAdidName("常规大图 1:1-创意1");
				adPlanOverviewVo.setAdvertid("17209785");
				adPlanOverviewVo.setBudget(new BigDecimal(0));
				adPlanOverviewVo.setPricing(new BigDecimal(0));
				adPlanOverviewVo.setStatus("STATUS_DENIED");
				adPlanOverviewVo.setStartTime("2020-12-08");
				adPlanOverviewVo.setEndTime("");
				adPlanOverviewVo.setCampaignId("168673633");
				adPlanOverviewVo.setCtype("8");
				adPlanOverviewVo.setAdgroupId("346169453");
				adPlanOverviewVo.setConvertName("OPTIMIZATIONGOAL_CLICK");
				adPlanOverviewVoList.add(adPlanOverviewVo);
			}
			for (AdPlanOverviewVo adPlanOverviewVo : adPlanOverviewVoList) {
				if ((null == req.getShowRatio() || 0 == req.getShowRatio())) {
					//operate== 1 需要处理对应的分成金额，对应早期的版本

					//显示分成后金额 [新增充值金额，活跃充值金额，首日充值金额，累计充值金额]
					//显示分成后金额 [新增充值金额，活跃充值金额，首日充值金额，累计充值金额]
					BigDecimal rt = new BigDecimal(0);
					if (StringUtils.isNotBlank(adPlanOverviewVo.getRatio())) {
						//分成百分百
						rt = new BigDecimal(adPlanOverviewVo.getRatio()).divide(new BigDecimal(100));
					}
					adPlanOverviewVo.setNewuuidfees(adPlanOverviewVo.getNewuuidfees().subtract(adPlanOverviewVo.getNewuuidfees().multiply(rt)));
					adPlanOverviewVo.setPayuuidfees(adPlanOverviewVo.getPayuuidfees().subtract(adPlanOverviewVo.getPayuuidfees().multiply(rt)));
					adPlanOverviewVo.setWorth1(adPlanOverviewVo.getWorth1().subtract(adPlanOverviewVo.getWorth1().multiply(rt)));
					adPlanOverviewVo.setWorth7(adPlanOverviewVo.getWorth7().subtract(adPlanOverviewVo.getWorth7().multiply(rt)));
					adPlanOverviewVo.setWorth30(adPlanOverviewVo.getWorth30().subtract(adPlanOverviewVo.getWorth30().multiply(rt)));

				}

				if (StringUtils.isNotBlank(req.getQueryColumn())) {
					if (StringUtils.isBlank(adPlanOverviewVo.getOs())) {
						adPlanOverviewVo.setOs("android");
					}
					adPlanOverviewVo.setOs(managerOs(adPlanOverviewVo.getOs()));
					String schduleType = adPlanOverviewVo.getStartTime() + "至" + (StringUtils.isNotBlank(adPlanOverviewVo.getEndTime()) ? adPlanOverviewVo.getEndTime() : "不限");
					adPlanOverviewVo.setScheduleType(schduleType);
					adPlanOverviewVo.setStatus(transValue(adPlanOverviewVo.getStatus()));
					adPlanOverviewVo.setDeliveryRange(transValue(adPlanOverviewVo.getDeliveryRange()));
					adPlanOverviewVo.setUnionVideoType(transValue(adPlanOverviewVo.getUnionVideoType()));
					adPlanOverviewVo.setInventoryType(inventory(adPlanOverviewVo.getInventoryType()));
				}

			}

		}

		return adPlanOverviewVoList;
	}

	/**
	 * 处理显示字段名称
	 *
	 * @return
	 */
	@Deprecated
	public String managerOs(String param) {
		switch (param) {
			case "0":
				return "android";
			case "1":
				return "IOS";
			case "3":
				return "OTHERS或为空";
			case "4":
				return "H5";
			case "5":
				return "PC";
		}
		return param;
	}

}
